package org.smallreunion.controller.ajax.bbs;

import java.util.HashMap;
import java.util.Map;

import org.slim3.datastore.S3QueryResultList;
import org.slim3.util.RequestMap;
import org.smallreunion.controller.ajax.JsonController;
import org.smallreunion.model.BBSPost;
import org.smallreunion.service.BBSService;

/**
 * BBSPost取得コントローラ
 *
 * @author Sinmetal
 *
 */
public class GetjsonController extends JsonController {

    private BBSService bbsService = new BBSService();

    /**
     * BBSPost取得
     */
    @Override
    protected Map<String, Object> handle() throws Exception {
        RequestMap requestMap = new RequestMap(request);
        String cursor = getCursor(requestMap);
        S3QueryResultList<BBSPost> bbsPostList =
            bbsService.getBBSPostList(cursor);
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("cursor", bbsPostList.getEncodedCursor());
        ret.put("hasNext", bbsPostList.hasNext());
        ret.put("bbsPostList", bbsPostList);
        return ret;
    }

    /**
     * 掲示板投稿取得
     *
     * @param requestMap
     * @return
     */
    protected S3QueryResultList<BBSPost> getBBSPostList(RequestMap requestMap) {
        final String HASHTAG = "hashtag";

        String cursor = getCursor(requestMap);
        if (requestMap.containsKey(HASHTAG)) {
            String hashtag = requestMap.get(HASHTAG).toString();
            return bbsService.getBBSPostListByHashtag(hashtag, cursor);
        }
        return bbsService.getBBSPostList(cursor);
    }

    /**
     * ページングのためのカーソルを取得
     *
     * @param requestMap
     * @return
     */
    protected String getCursor(RequestMap requestMap) {
        final String key = "cursor";
        if (requestMap.containsKey(key)) {
            return requestMap.get(key).toString();
        }
        return "";
    }
}
